package org.example.data_stream;

import cn.hutool.core.util.RandomUtil;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
public class E03_CustomSource {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

//        DataStreamSource<Event> clickSource = env.addSource(new ClickSource(), "Click Source").setParallelism(1);
        DataStreamSource<Event> clickSource = env.addSource(new ParallelClickSource(), "Click Source").setParallelism(2);

        clickSource.print();

        env.execute();
    }

    /**
     * 用户点击源
     * @author shenguangyang

     */
    static class ClickSource implements SourceFunction<Event> {
        // 声明一个标志位
        private volatile Boolean cancel = false;

        @Override
        public void run(SourceContext<Event> ctx) throws Exception {
            String[] users = {"Mary", "Alice", "Bod", "Cary"};
            String[] urls = {"./home", "./cart", "./fav", "./prod?id=100", "./prod?id=10"};
            while (!cancel) {
                ctx.collect(new Event(users[RandomUtil.randomInt(0, users.length)], urls[RandomUtil.randomInt(0, urls.length)], System.currentTimeMillis()));
                TimeUnit.MILLISECONDS.sleep(200);
            }
        }

        @Override
        public void cancel() {
            this.cancel = true;
        }
    }

    /**
     * @author shenguangyang

     */
    static class ParallelClickSource implements ParallelSourceFunction<Event> {
        // 声明一个标志位
        private volatile Boolean cancel = false;

        @Override
        public void run(SourceContext<Event> ctx) throws Exception {
            String[] users = {"xh", "Alice", "Bod", "Cary"};
            String[] urls = {"./home", "./cart", "./fav", "./prod?id=100", "./prod?id=10"};
            while (!cancel) {
                ctx.collect(new Event(users[RandomUtil.randomInt(0, users.length)], urls[RandomUtil.randomInt(0, urls.length)], System.currentTimeMillis()));
                TimeUnit.MILLISECONDS.sleep(200);
            }
        }

        @Override
        public void cancel() {
            this.cancel = true;
        }
    }
}

